import pymongo
import os
import uuid
from datetime import datetime as dt

myclient = pymongo.MongoClient("mongodb://127.0.0.1:27017/")
mydb = myclient['db']  # 总数据库
sign_col = mydb['sign']  # 签订信息集合

# 创建签到
def createSign(openid, signDic):
    global signNum
    signId = str(uuid.uuid4())
    sign_list = []
    signDic['signId'] = signId
    signDic['c_openId'] = openid

    try:
        openid_signs = sign_col.find({'c_openId': openid})[0] # openid唯一，所以选第0个数据就可以
        # print(openid_signs['signs'])
        for item in openid_signs['signs']:
            sign_list.append(item)
            # print(item)
        sign_list.append(signDic)
        # print(sign_list)
        dict = {'c_openId': openid, 'signs': sign_list}
        # 更新数据库
        sign_col.update_one({'c_openId': openid}, {"$set": {'signs': sign_list}})
    except Exception as e:  # 第一次没有数据的情况
        print(e)
        dict = {'c_openId': openid, 'signs': [signDic]}
        sign_col.insert_one(dict)

    return signId  # 返回签到的编号

def updateSign(openid, signDic):
    sign_list = []
    signId = signDic['signId']
    signInfo = {} # 要返回的签到的完整信息
    openid_signs = sign_col.find({'c_openId': openid})[0] # openid唯一，所以选第0个数据就可以
    # print(openid_signs['signs'])
    for item in openid_signs['signs']:
        sign_list.append(item)
    for item in sign_list:
        if item['signId'] == signId:
            key_list = item.keys()
            for key in key_list:
                if item[key] != signDic[key]:
                    item[key] = signDic[key]
            if not item.get('rule'):
                item['rule'] = signDic['rule']
            # signInfo = item
            break
    # 对数据库相应签到进行更新
    sign_col.update_one({'c_openId': openid}, {"$set": {'signs': openid_signs['signs']}})
    # return signInfo

# 查询签到
def viewSigns(openid):
    signs = []
    try:
        # print(sign_col.find({'c_openId': openid})[0])
        openid_signs = sign_col.find({'c_openId': openid})[0]
        for item in openid_signs['signs']:
            signs.append(item)
    except Exception as e:
        pass

    # print(signs)
    return signs

# 查询某个签到的具体信息
def viewOneSign(openid, signid):
    openid_signs = sign_col.find({'c_openId': openid})[0]
    oneSign = {}
    for item in openid_signs['signs']:
        if item['signId'] == signid:
            oneSign = item
            break
    return oneSign

# 添加签到人的信息
# c_openId 为发起人的openId
# signID 为签到的ID
# signerInfo 为签到人信息，是一个字典
def addSigner(c_openid, signID, signerInfo):
    # c_openId 为发起人的openId
    openid_signs = sign_col.find({'c_openId': c_openid})[0]
    for item in openid_signs['signs']:
        if item['signId'] == signID:
            if item.get('signers'):
                item['signers'].append(signerInfo)
            else:
                item['signers'] = [signerInfo]  # 为查找到的签到添加一个学生键值对

    # 对数据库相应签到进行更新
    sign_col.update_one({'c_openId': c_openid}, {"$set": {'signs': openid_signs['signs']}})

# 查询某个签中所有签到人信息
def viewAllSighers(c_openId, signId):
    signers = []
    openid_signs = sign_col.find({'c_openId': c_openId})[0]
    for item in openid_signs['signs']:
        if item['signId'] == signID:
            signers = item['signers']
    return signers

# 签到信息加入数据库
# s_openId 签到者的id
def signIn(c_openId, signId, s_openId):
    openid_signs = sign_col.find({'c_openId': c_openId})[0]
    for item in openid_signs['signs']:
        if item['signId'] == signId:
            for signer in item['signers']:
                if s_openId == signer['member_openid']:
                    if signer.get('signIn'):
                        signer['signIn'].append({'signTime': dt.now().strftime('%Y-%m-%d %H:%M:%S')})
                    else:
                        signer['signIn'] = [{'signTime': dt.now().strftime('%Y-%m-%d %H:%M:%S')}]
                    print(signer)
    # 对数据库相应签到进行更新
    sign_col.update_one({'c_openId': c_openId}, {"$set": {'signs': openid_signs['signs']}})
